export function isSleeping () {
    const p3dm = cc.director.getPhysics3DManager();
    var bodys = p3dm.physicsWorld.world.bodies;

    let isSleep = true;
    bodys.forEach(bi => {
        if (bi.type != CANNON.Body.STATIC && !bi.isSleeping()) {
            isSleep = false;
        }
    });
    return isSleep; // CANNON.World['SLEEPING'];
}

export function setWorldPosition (node: cc.Node, wp: cc.Vec3) {
    node['setWorldPosition'](wp);
    const p3d = cc.director.getPhysics3DManager();
    if (p3d['useFixedDigit']) {
        const c3d = node.getComponent(cc.Collider3D);
        if (c3d) {
            const posDigit = p3d['fixDigits'].position;
            const pos = c3d.shape['sharedBody'].body.position;
            pos.x = parseFloat(wp.x.toFixed(posDigit));
            pos.y = parseFloat(wp.y.toFixed(posDigit));
            pos.z = parseFloat(wp.z.toFixed(posDigit));
        }
    }
}

export function setWorldRotation (node: cc.Node, wr: cc.Quat) {
    node['setWorldRotation'](wr);
    const p3d = cc.director.getPhysics3DManager();
    if (p3d['useFixedDigit']) {
        const c3d = node.getComponent(cc.Collider3D);
        if (c3d) {
            const rotDigit = p3d['fixDigits'].rotation;
            const rot = c3d.shape['sharedBody'].body.quaternion;
            rot.x = parseFloat(wr.x.toFixed(rotDigit));
            rot.y = parseFloat(wr.y.toFixed(rotDigit));
            rot.z = parseFloat(wr.z.toFixed(rotDigit));
            rot.w = parseFloat(wr.w.toFixed(rotDigit));
        }
    }
}

// export function getDynamicsData () {
//     const p3dm = cc.director.getPhysics3DManager();
//     const bodies = p3dm['physicsWorld'].world.bodies as CANNON.Body[];
//     const dynamics = {};
//     for (let i = 0; i < bodies.length; i++) {
//         const bi = bodies[i];
//         if (bi.type != CANNON.Body.STATIC) {
//             dynamics[bi.id] = {
//                 p: bi.position,
//                 q: bi.quaternion
//             }
//         }
//     }
//     return dynamics;
// }

export function getDynamicsData (dynamics) {
    var p3dm = cc.director.getPhysics3DManager();
    var bodies = p3dm['physicsWorld'].world.bodies;
    for (var i = 0; i < bodies.length; i++) {
        var bi = bodies[i];
        if (bi.type != CANNON.Body.STATIC) {
            dynamics[bi.id] = {
                p: bi.position,
                q: bi.quaternion
            }
        }
    }
    return dynamics;
}

export function setDynamicsData (dynamics) {
    for (var j in dynamics) {
        const bj = CANNON.World['idToBodyMap'][j];
        if (bj) {
            bj.position.copy(dynamics[j].p);
            bj.quaternion.copy(dynamics[j].q);
        }
    }
}
